import { Component, OnInit, Inject, AfterViewChecked, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

import { ForumService } from '../../service/ForumService';
import { NewsCategory } from '../../models/NewsCategory';


@Component({
  templateUrl: './addType.html',
  styleUrls: ['./addType.css']
})
export class AddTypeComponent implements OnInit, AfterViewChecked {

  messages = {
    newsName: '',
  };
  categorys: NewsCategory[];
  category: NewsCategory;
  constructor(
    private dialogRef: MatDialogRef<AddTypeComponent>,
    private  forumService: ForumService,
    @Inject(MAT_DIALOG_DATA) public data: {categorys: NewsCategory[]}
  ) {
    this.categorys = data.categorys;
  }

  @ViewChild('forumTypeForm')
  forumTypeForm: NgForm;

  ngAfterViewChecked() {
    if (this.forumTypeForm) {
      this.forumTypeForm.valueChanges.subscribe(data => this.checkValidate());
    }
  }

  ngOnInit() {
    this.category = {};
  }

  onSubmit() {
    this.checkValidate(true);
    if (this.forumTypeForm.invalid) {
      // 触发mat的error
      this.forumTypeForm.onSubmit(null);
      return false;
    }
      this.forumService.insertCategory(this.category).subscribe((res) => {
        this.dialogRef.close(res.res);
      });



  }

  checkValidate(isSubmit?: boolean) {
    const form = this.forumTypeForm;

    for (const field in AddTypeComponent.ErrorMessages) {

      const control = form.controls[field];

      if (control && control.valid) {
        this.messages[field] = '';
      }
      if (control && (control.dirty || isSubmit) && !control.valid) {
        const messages = AddTypeComponent.ErrorMessages[field];
        if (control.errors) {
          this.messages[field] = messages[Object.keys(control.errors)[0]];
        }
      }

    }
  }

  static ErrorMessages = {
    newsName: {
      required: '类型名称不能为空'
    }
  };
}
